package com.imooc.controller.intercept;

import com.alibaba.druid.support.json.JSONUtils;
import com.imooc.utils.IMoocJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

public class MInterceptor implements HandlerInterceptor {
    @Autowired
    public RedisOperator redisOperator;

    public static final String USER_REDIS_SESSION = "user_redis_session";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //返回值 false 表示拦截  true表示放行
        String userId = request.getHeader("userId");
        String userToken = request.getHeader("userToken");
        //查询用户token
        System.out.println("userId:" + userId);
        System.out.println("userToken:" + userToken);

        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(userToken)
               // &&  userToken != "[object Undefined]"&&  userId != "[object Undefined]"
        ) {
            //判断用户 userToken 是否有效
            String uniqueToken = redisOperator.get(USER_REDIS_SESSION + ":" + userId);
            if (StringUtils.isEmpty(uniqueToken) || StringUtils.isBlank(uniqueToken)) {
                //登录超时
                returnErrorResponse(response, IMoocJSONResult.errorMsg("登录超时"));
                return false;
            } else {
                if (!uniqueToken.equals(userToken)) {
                    //单点登录
                    returnErrorResponse(response, IMoocJSONResult.errorMsg("在其他设备登录"));
                    return false;
                } else {
                    redisOperator.expire(USER_REDIS_SESSION + ":" + userId, 60 * 30);
                    return true;
                }


            }
        } else {
            returnErrorResponse(response, IMoocJSONResult.errorMsg("用户未登录,检查header验证参数"));
            return false;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


    public void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result) throws IOException {

        OutputStream out = null;

        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();

            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();

        } finally {
            if (out != null)
                out.close();
        }


    }

}
